package cn.org.timespace.ons.inside.mina.filter;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class ESInProtocolEncoder implements ProtocolEncoder {

	private final AttributeKey ENCODER = new AttributeKey(getClass(), "encoder");

	private final Charset charset;
	
    public ESInProtocolEncoder(Charset charset) {
        this.charset = charset;
    }
    
    //在此处实现对ESCardProtocalPack包的编码工作，并把它写入输出流中
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    	CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);
    	if (encoder == null) {
    	     encoder = charset.newEncoder();
    	     session.setAttribute(ENCODER, encoder);
    	}

    	//延时一秒发送
    	Thread.sleep(500L);
    	
    	IoBuffer buf = null;
    	if(message instanceof ESInProtocalPack) {
			ESInProtocalPack pack = (ESInProtocalPack) message;
			
			int totalLength = pack.getPackageLengthInt() + 15;
			
			// 使用指定大小实例化一个新的Buffer
	        buf = IoBuffer.allocate(totalLength).setAutoExpand(true);
	        buf.putString((CharSequence)pack.toString(), encoder);
    	}
    	else {
    		String value = (String)message;
    		buf = IoBuffer.allocate(value.length()).setAutoExpand(true);
	        buf.putString((CharSequence)value, encoder);
    	}
    	buf.flip();
        out.write(buf);
    }
    
	@Override
	public void dispose(IoSession iosession) throws Exception {
		
	}
}
